package com.zkadmin.renderer;

import java.util.HashMap;
import java.util.Map;

import org.apache.shiro.SecurityUtils;
import org.springframework.orm.ObjectOptimisticLockingFailureException;
import org.zkoss.zk.ui.Executions;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.event.EventListener;
import org.zkoss.zk.ui.event.Events;
import org.zkoss.zul.Button;
import org.zkoss.zul.Hbox;
import org.zkoss.zul.Listitem;
import org.zkoss.zul.ListitemRenderer;
import org.zkoss.zul.Messagebox;
import org.zkoss.zul.Textbox;
import org.zkoss.zul.Window;

import com.zkadmin.constraints.RolelConstraint;
import com.zkadmin.controller.RoleListCtrl;
import com.zkadmin.entity.SysRole;
import com.zkadmin.service.SysRoleService;
import com.zkadmin.util.AdminConstants;
import com.zkadmin.util.AdminWebUtils;
import com.zkadmin.util.MsgBox;

public class SysRoleListRenderer extends BaseRenderer implements ListitemRenderer<SysRole> {
	private SysRoleService sysRoleService;
	private RoleListCtrl roleListCtrl;
	private Window win;

	public SysRoleListRenderer(Window win, RoleListCtrl roleListCtrl, SysRoleService sysRoleService) {
		this.sysRoleService = sysRoleService;
		this.roleListCtrl = roleListCtrl;
		this.win = win;
	}

	@Override
	public void render(Listitem listitem, final SysRole role, int index) throws Exception {
		if ((SecurityUtils.getSubject().hasRole(AdminConstants.ROLE_ADMIN) || SecurityUtils.getSubject().isPermitted("sys:role:update")) && !role.getName().equalsIgnoreCase(AdminConstants.ROLE_ADMIN)) {
			final Textbox roleBox = new Textbox(role.getRole());
			roleBox.setInplace(true);
			roleBox.setWidth("90%");
			roleBox.setMaxlength(50);
			roleBox.setParent(createListcell(listitem));
			roleBox.setConstraint(new RolelConstraint());
			roleBox.addEventListener(Events.ON_CHANGE, new EventListener<Event>() {
				@Override
				public void onEvent(Event event) throws Exception {
					SysRole newSysRole = sysRoleService.findByRole(roleBox.getValue());
					if (newSysRole != null && !newSysRole.equals(role)) {
						MsgBox.alert("【" + roleBox.getValue() + "】角色已经存在。");
						roleListCtrl.refreshData();
						return;
					}
					role.setRole(roleBox.getValue());
					saveAndRefresh(role);
				}

			});

			final Textbox nameBox = new Textbox(role.getName());
			nameBox.setInplace(true);
			nameBox.setWidth("90%");
			nameBox.setMaxlength(20);
			nameBox.setParent(createListcell(listitem));
			nameBox.setConstraint("no empty");
			nameBox.addEventListener(Events.ON_CHANGE, new EventListener<Event>() {
				@Override
				public void onEvent(Event event) throws Exception {
					SysRole newSysRole = sysRoleService.findByName(nameBox.getValue());
					if (newSysRole != null && !newSysRole.equals(role)) {
						MsgBox.alert("【" + nameBox.getValue() + "】角色名称已经存在。");
						roleListCtrl.refreshData();
						return;
					}

					role.setName(nameBox.getText());
					saveAndRefresh(role);
				}
			});
		} else {
			createListcell(listitem).setLabel(role.getRole());
			createListcell(listitem).setLabel(role.getName());
		}

		Hbox hbox = createHbox(listitem);
		if (!role.getRole().equalsIgnoreCase(AdminConstants.ROLE_ADMIN)) {
			final Button resourceBtn = new Button("资源授权");
			if (!SecurityUtils.getSubject().hasRole(AdminConstants.ROLE_ADMIN)) {
				resourceBtn.setVisible(SecurityUtils.getSubject().isPermitted("sys:role:resource"));
			}
			resourceBtn.setIconSclass("z-icon-check-square-o");
			hbox.appendChild(resourceBtn);
			resourceBtn.addEventListener(Events.ON_CLICK, new EventListener<Event>() {
				@Override
				public void onEvent(Event event) throws Exception {
					Map<String, Object> args = new HashMap<String, Object>();
					args.put("roleId", role.getId());
					Window window = (Window) Executions.createComponents(AdminWebUtils.getZulPagePath("admin/role_resource_dialog.zul"), win, args);
					window.addEventListener(AdminConstants.EVENT_ONREFRESH, new EventListener<Event>() {
						@Override
						public void onEvent(Event event) throws Exception {
							roleListCtrl.refreshData();
						}
					});
					AdminWebUtils.addCaption(window, resourceBtn.getIconSclass());
					window.doModal();
				}
			});

			Button delBtn = new Button("删除");
			if (!SecurityUtils.getSubject().hasRole(AdminConstants.ROLE_ADMIN)) {
				delBtn.setVisible(SecurityUtils.getSubject().isPermitted("sys:role:delete"));
			}
			delBtn.setIconSclass("z-icon-times");
			hbox.appendChild(delBtn);
			delBtn.addEventListener(Events.ON_CLICK, new EventListener<Event>() {
				@Override
				public void onEvent(Event event) throws Exception {
					Messagebox.show("是否删除此角色？", "删除确认", Messagebox.YES | Messagebox.NO, Messagebox.QUESTION, new EventListener<Event>() {
						@Override
						public void onEvent(Event event) throws Exception {
							if (Messagebox.ON_YES.equals(event.getName())) {
								sysRoleService.delete(role.getId());
								roleListCtrl.refreshData();
							}

						}
					});
				}
			});
		}
	}

	private void saveAndRefresh(final SysRole role) {
		try {
			sysRoleService.save(role);
		} catch (ObjectOptimisticLockingFailureException e) {
			MsgBox.alert(AdminConstants.getErrorDataVersionMessage());
		} finally {
			roleListCtrl.refreshData();
		}
	}
}
